package com.tc.juc.pack06;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @Auther: tianchao
 * @Date: 2021/10/7 01:06
 * @Description:
 */
public class TestUnSafe {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe)theUnsafe.get(null);


        Teacher teacher = new Teacher();
        //1 获取域的偏移地址
        long idOffset = unsafe.objectFieldOffset(teacher.getClass().getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(teacher.getClass().getDeclaredField("name"));
        System.out.println(unsafe.compareAndSwapInt(teacher, idOffset, 0, 5));
        System.out.println(unsafe.compareAndSwapObject(teacher, nameOffset, null, "李四"));
        System.out.println(teacher);
    }
}

@Data
class Teacher{
    volatile int id;
    volatile String name;
}
